package cloud.topdaddy.admin.system.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cloud.topdaddy.admin.system.entity.SysRole;
import cloud.topdaddy.admin.system.entity.SysRoleMenu;
import cloud.topdaddy.admin.system.service.SysRoleMenuService;
import cloud.topdaddy.admin.system.service.SysRoleService;
import cloud.topdaddy.base.common.resp.R;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Caching;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/role")
public class SysRoleController {

    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private SysRoleMenuService sysRoleMenuService;

    @GetMapping("/list")
    @SaCheckLogin
    @SaCheckPermission("system:role:list")
    public R<List<SysRole>> list() {
        return R.ok(sysRoleService.list());
    }

    @GetMapping("/{roleId}")
    @SaCheckLogin
    public R<SysRole> get(@PathVariable("roleId") Long roleId) {
        return R.ok(sysRoleService.getById(roleId));
    }

    @PostMapping("/add")
    @SaCheckLogin
    @SaCheckPermission("system:role:add")
    public R<String> add(@RequestBody @Valid SysRole role) {
        role.setCreateTime(LocalDateTime.now());
        sysRoleService.save(role);
        return R.ok("新增成功");
    }

    @PutMapping("/update")
    @SaCheckLogin
    @SaCheckPermission("system:role:update")
    public R<String> update(@RequestBody @Valid SysRole role) {
        role.setUpdateTime(LocalDateTime.now());
        sysRoleService.updateById(role);
        return R.ok("更新成功");
    }

    @DeleteMapping("/delete/{roleId}")
    @SaCheckLogin
    @SaCheckPermission("system:role:delete")
    @Caching(evict = {
        @CacheEvict(cacheNames = "auth:perms#10m", allEntries = true),
        @CacheEvict(cacheNames = "auth:myMenus#5m", allEntries = true),
        @CacheEvict(cacheNames = "auth:myPerms#5m", allEntries = true)
    })
    public R<String> delete(@PathVariable("roleId") Long roleId) {
        sysRoleService.removeById(roleId);
        // 可选：同时清理角色菜单关系
        sysRoleMenuService.lambdaUpdate().eq(SysRoleMenu::getRoleId, roleId).remove();
        return R.ok("删除成功");
    }

    @PostMapping("/{roleId}/menus")
    @SaCheckLogin
    @SaCheckPermission("system:role:assign-menu")
    @Caching(evict = {
        @CacheEvict(cacheNames = "auth:perms#10m", allEntries = true),
        @CacheEvict(cacheNames = "auth:myMenus#5m", allEntries = true),
        @CacheEvict(cacheNames = "auth:myPerms#5m", allEntries = true)
    })
    public R<String> assignMenus(@PathVariable("roleId") Long roleId, @RequestBody List<Long> menuIdList) {
        // 清空原有关系
        sysRoleMenuService.lambdaUpdate().eq(SysRoleMenu::getRoleId, roleId).remove();
        // 新增
        if (menuIdList != null && !menuIdList.isEmpty()) {
            LocalDateTime now = LocalDateTime.now();
            List<SysRoleMenu> batch = menuIdList.stream().map(mid -> {
                SysRoleMenu rm = new SysRoleMenu();
                rm.setRoleId(roleId);
                rm.setMenuId(mid);
                rm.setCreateTime(now);
                rm.setUpdateTime(now);
                return rm;
            }).toList();
            sysRoleMenuService.saveBatch(batch);
        }
        return R.ok("分配成功");
    }
}